package com.zhieasy.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.ObjectUtil;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.github.pagehelper.PageInfo;
import com.zhieasy.common.annotation.AccessLimit;
import com.zhieasy.common.api.CommonResult;
import com.zhieasy.common.api.LayuiTableResult;
import com.zhieasy.common.util.FilesUtil;
import com.zhieasy.common.util.JwtUtil;
import com.zhieasy.domain.Admin;
import com.zhieasy.domain.Student;
import com.zhieasy.domain.StudentVo;
import com.zhieasy.service.AdminService;
import com.zhieasy.service.StudentListRedisService;
import com.zhieasy.service.StudentService;
import io.netty.util.internal.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 风亦未止
 * @date 2021/11/25 17:32
 */
@Api(tags = "管理员接口")
@RestController
@RequestMapping("admin")
public class AdminController {
    @Autowired
    private StudentService studentService;
    @Autowired
    private StudentListRedisService studentListRedisService;
    @Autowired
    private AdminService adminService;
    @Resource
    private FilesUtil fileDfsUtil;

    @PostConstruct
    //缓存处理
    public void savaRedis(){
        List<StudentVo> all = studentService.getAll(null);
        studentListRedisService.set(all);
    }

    @ApiOperation(value = "条件查询获取学生列表")
    @GetMapping("/getList")
    public LayuiTableResult getList(@RequestParam(value = "page",defaultValue = "1") @ApiParam(value = "页码") int pageNum,
                                    @RequestParam(value = "limit",defaultValue = "15") @ApiParam(value = "每页条数") int pageSize, Student student){
        String ip="https://files.zhiyitimetable.cn/";
        //在线预览api
        String onlineAPI="https://file.zhiyitimetable.cn/onlinePreview?url=";
        List<StudentVo> all = studentService.getAll(student);
        PageInfo<StudentVo> list = studentService.getList(pageNum, pageSize, student);
        list.getList().stream().forEach(studentVo -> {
            String fileUrl=ip+studentVo.getFilePath();
            String encode="";
            try {
                //文件地址转码
                encode = URLEncoder.encode(Base64.encode(fileUrl), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            studentVo.setFilePath(StringUtil.isNullOrEmpty(studentVo.getFilePath())?"未提交简历":"<a href=\""+onlineAPI+encode+"\"target=\"view_window\">查看简历</a>");
        });
        LayuiTableResult layuiTableResult = new LayuiTableResult(0, "成功！", all.size(), list.getList());
        return layuiTableResult;
    }

    @ApiOperation(value = "获取学生数量提交简历数")
    @GetMapping("/getInfo")
    public CommonResult getInfo(){
        Integer studentNum = studentService.getStudentNum();
        Integer submitNum = studentService.getSubmitNum();
        Map<String,Integer> data=new HashMap<>(2);
        data.put("studentNum",studentNum);
        data.put("submitNum",submitNum);
        return CommonResult.success(data);
    }

    @ApiOperation(value = "刷新缓存")
    @PostMapping("/fresh")
    public void fresh(){
        savaRedis();
    }

    @ApiOperation(value = "更新用户状态")
    @PostMapping("/update")
    public CommonResult update(Student student){
        boolean b = studentService.updateById(student);
        if (b){
            return CommonResult.success(null,"操作成功！");
        }
        return CommonResult.failed("操作失败！");
    }
    @ApiOperation(value = "管理员登录")
    @PostMapping("/login")
    public CommonResult login(@RequestParam("username") @ApiParam(value = "用户名") String username,
                              @RequestParam("password") @ApiParam(value = "密码") String password){
        Admin admin = adminService.getById(username);
        if (ObjectUtil.isNull(admin)){
            return CommonResult.failed("用户名不存在！");
        }
        if (password.trim().equals(admin.getPassword())){
            String tokenByAdmin = JwtUtil.getTokenByAdmin(admin);
            return CommonResult.success(tokenByAdmin,"登录成功！");
        }
        return CommonResult.failed("密码错误！");
    }

    @ApiOperation(value = "简历下载")
    @GetMapping("/download/{studentId}")
    public void download(@PathVariable("studentId") @ApiParam(value = "用户id") String studentId, HttpServletResponse response) throws IOException {
        Student student = studentService.getById(studentId);
        String name=student.getStudentName();
        String filePath=student.getFilePath();
        //下载的文件名
        response.setContentType("application/octet-stream");
        response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(name,"utf-8"));
        //下载对应的文件
        byte[] bytes = fileDfsUtil.downloadFile(filePath);

        response.getOutputStream().write(bytes);
        // 刷新缓存
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }

    @ApiOperation(value = "学习方向审核通过")
    @PostMapping("/setDirection/{studentId}")
    public CommonResult setDirection(@PathVariable("studentId") @ApiParam(value = "用户id") String studentId){
        Student student = studentService.getById(studentId);
        Integer directionId = student.getDirectionId();
        Integer newId=0;
        switch (directionId){
            case -1:
                newId=1;
                break;
            case -2:
                newId=2;
                break;
            case -3:
                newId=3;
                break;
            case -4:
                newId=4;
                break;
            case -5:
                newId=5;
                break;
            case -6:
                newId=6;
                break;
            case -7:
                newId=7;
                break;
            case -8:
                newId=8;
                break;
            default:
                newId=null;
        }
        student.setDirectionId(newId);
        boolean b = studentService.updateById(student);
        if (b){
            return CommonResult.success(null,"操作成功！");
        }
        return CommonResult.failed("操作失败！");
    }

    @ApiOperation(value = "学习方向审核不通过")
    @PostMapping("/rejectDirection/{studentId}")
    public CommonResult rejectDirection(@PathVariable("studentId") @ApiParam(value = "用户id") String studentId){
        Student student = studentService.getById(studentId);
        student.setDirectionId(-10);
        boolean b = studentService.updateById(student);
        if (b){
            return CommonResult.success(null,"操作成功！");
        }
        return CommonResult.failed("操作失败！");
    }

}
